package com.yuhang.demo.ExcelListener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yuhang.demo.common.MD5;
import com.yuhang.demo.entity.UserEntity;
import com.yuhang.demo.entity.UserExtendEntity;
import com.yuhang.demo.entity.excel.UserData;
import com.yuhang.demo.exceptionHandler.MyException;
import com.yuhang.demo.service.UserService;

/**
 * @author yyh
 * @create 2020-09-08 20:56
 */
public class UserExcelListener extends AnalysisEventListener<UserData> {

    //因为ExcelListener不交给spring进行管理，需要自己new，不能注入其他对象

    public UserService userService;
    public UserExcelListener() {}
    public UserExcelListener(UserService userService) {
        this.userService = userService;
    }

    //读取excel内容，一行一行进行读取
    @Override
    public void invoke(UserData userData, AnalysisContext analysisContext) {
        if (userData == null) {
            throw new MyException(20001, "文件数据为空");
        }

        //一行一行读取，每次读取有N个值
        UserEntity user = new UserEntity();
        user.setName(userData.getName());
        user.setPhone(userData.getPhone());
        user.setPassword(userData.getPassword());
        user.setEnableStatus(userData.getEnableStatus());

        //加密
        user.setPassword( MD5.encrypt(user.getPassword()));

        //判断手机号
        Boolean number = userService.isPhoneNumber(user.getPhone());

        //判断手机号是否重复
        boolean isRepeat = userService.repeatPhone(user.getPhone());


        if(number && !isRepeat){
            UserExtendEntity extend = new UserExtendEntity();
            extend.setCity(userData.getCity());
            extend.setCountry(userData.getCountry());
            extend.setProvince(userData.getProvince());

            userService.saveUser(user,extend);
        }


    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
